// pages/order/order.js

var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    alllist:[],  
    cartList:[],    //购物车商品列表
    mut:false,
    toView:"to0",
    scrollTop:0,   //到顶部的距离
    currentLeft:0, //左侧选中的下标
    totalPrice:0,   //购物车商品总价
    totalNum:0,     //商品数量
    //购物车动画
    animationData:{},
    animationMask:{},
    maskVisual:"hidden",
    maskFlag:true,
  },
  heightArr:[],  //右侧分类列表的高度累加数组
  distance:0,    //记录scroll-view滚动过程中距离顶部的高度 
  flag:0, //判断购物车是否打开

  onShow:function(options){
    var that = this;
    // 获取购物车缓存数据
    var arr = wx.getStorageSync('cart') || [];
    // 进入页面后判断购物车是否有数据，如果有，将菜单与购物车quantity数据统一
    if (arr.length > 0){
      for (var i in arr){
        for (var j in that.data.alllist){
          for (var k in that.data.alllist[j].infor){
            if(that.data.alllist[j].infor[k].cookId == arr[i].cookId){
              that.data.alllist[j].infor[k].quantity=ar[i].quantity;
              break;
            }
            else{
              that.data.alllist[j].infor[k].quantity=0;
            }
          }
        }
      }
    }
    else{
      for(var j in that.data.alllist){
        for (var k in that.data.alllist[j].infor){
          that.data.alllist[j].infor[k].quantity=0;
        }
      }
    }
    // 进入页面计算购物车总价、总数
    var totalPrice = 0;
    var totalNum = 0;
    if (arr.length > 0) {
      for (var i in arr) {
        totalPrice += arr[i].price * arr[i].quantity;
        totalNum += Number(arr[i].quantity);
      }
    }
    // 赋值数据
    this.setData({
      cartList: arr,
      alllist: that.data.alllist,
      totalPrice: totalPrice.toFixed(2),
      totalNum: totalNum
    })
  },
  //增加数量
  addCart:function(e){
    var id = e.currentTarget.dataset.id;
    var arr = wx.getStorageSync('cart') || [];
    var f = false;
    var t = 0;
    var temlist = [];
    for(var i in this.data.alllist){
      for(var j in this.data.alllist[i].infor){//遍历菜单找到被点击商品，数量加1
        if(this.data.alllist[i].infor[j].cookId == id){
          this.data.alllist[i].infor[j].quantity += 1;
          if(t<1){
            temlist[t] = this.data.alllist[i].infor[j]; 
            t++;
          }
        } 
      }
    }
    if(arr.length > 0){ //遍历购物车，找到被点击商品数量加1
      for(var k in arr){
          if(arr[k].cookId == id){//如果购物车中有该商品，数量加1
            console.log("K:"+k)
            arr[k].quantity += 1;
            f = true;
            try{
              wx.setStorageSync('cart', arr)
            }catch(e){
              console.log(e)
            }
          }
      }
      if(!f){//购物车没有该商品，将该商品加入购物车
       arr.push(temlist[0]);
      }
    }
    else{//购物车中没有任何商品，直接将商品加入购物车
      arr.push(temlist[0]);  
    }
    try{
      wx.setStorageSync('cart', arr)
    }catch(e){
      console.log(e)
    }
    this.setData({
      cartList:arr,
      alllist:this.data.alllist
    })
    this.getTotalPrice()
  },
  //减少数量
  delCart:function(e){
    var id = e.currentTarget.dataset.id;
    var arr = wx.getStorageSync('cart') || [];
    for(var i in this.data.alllist){//遍历菜单 找到被点击商品数量-1
      for(var j in this.data.alllist[i].infor){
        if(this.data.alllist[i].infor[j].cookId == id){
          this.data.alllist[i].infor[j].quantity -= 1;
          if(this.data.alllist[i].infor[j].quantity <= 0){
            this.data.alllist[i].infor[j].quantity = 0;
          }
        }
      }
    }
    if(arr.length > 0){
      for(var k in arr){
        if(arr[k].cookId == id){
          arr[k].quantity -= 1;
          if(arr[k].quantity <= 0){
            this.removeByValue(arr,id)
          }
          if(arr.length <= 0){
            this.setData({
              alllist:this.data.alllist,
              cartList:[],
              totalNum:0,
              totalPrice:0,
            })
            this.cascadeDismiss() //关闭购物车
            this.flag = 0
          }
          try{
            wx.setStorageSync('cart', arr)
          }catch(e){
            console.log(e)
          }
        }
      }
    }
    this.setData({
      cartList:arr,
      alllist:this.data.alllist
    })
    this.getTotalPrice()
  },
  //根据id删除数组
  removeByValue:function(array, val){
    for(var i=0; i<array.length; i++){
      if(array[i].cookId == val){
        array.splice(i,1);
        break;
      }
    }
  },
  //总价和数量
  getTotalPrice:function(){
    var cartList = this.data.cartList;
    var totalP = 0;
    var totalN = 0;
    for(var i in cartList){
      totalP += cartList[i].quantity * cartList[i].price
      totalN += cartList[i].quantity
    }
    this.setData({
      carList:cartList,
      totalPrice:totalP.toFixed(2),
      totalNum:totalN
    });
  },
  //清空购物车
  cleanList:function(e){
    for(var i in this.data.alllist){
      for(var j in this.data.alllist[i].infor){
        this.data.alllist[i].infor[j].quantity = 0;
      }
    }
    try {
      wx.setStorageSync('cart', "")
    } catch (e) {
      console.log(e)
    }
    this.setData({
      alllist:this.data.alllist,
      cartList:[],
      cartFlag:false,
      totalNum:0,
      totalPrice:0
    })
    this.cascadeDismiss()
    this.flag = 0
  },

  //切换购物车开与关
  cascadeToggle:function(){
    var that = this;
    var arr = this.data.cartList
   
    if (arr.length > 0) {
      if (that.flag == 0) {
        that.cascadePopup(),
        that.flag = 1
      }
      else {
        that.cascadeDismiss(),
        that.flag = 0
      }
    }
    else {
      that.cascadeDismiss()
    }
  },

  // 打开购物车方法
  cascadePopup: function () {
    var that = this;
    // 购物车打开动画
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-in-out',
      delay: 0
    });
    that.animation = animation;
    animation.translate(0, -285).step();
    that.setData({
      animationData: that.animation.export(),
    });
    // 遮罩渐变动画
    var animationMask = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear',
    });
    that.animationMask = animationMask;
    animationMask.opacity(0.8).step();
    that.setData({
      animationMask: that.animationMask.export(),
      maskVisual: "show",
      maskFlag: false,
    });
  },
  // 关闭购物车方法
  cascadeDismiss: function () {
    var that = this
    // 购物车关闭动画
    that.animation.translate(0, 285).step();
    that.animation.export()
    that.setData({
      animationData: that.animation.export()
    });
    // 遮罩渐变动画
    that.animationMask.opacity(0).step();
    that.setData({
      animationMask: that.animationMask.export(),
    });
    // 隐藏遮罩层
    that.setData({
      maskVisual: "hidden",
      maskFlag: true
    });
  },

  //下单
  gotoOrder: function (ev) {
    var list = ev.currentTarget.dataset.list
    app.listdata = list
     wx.switchTab({
      url: '../take/take',
    }) 
  },

  selectHeight(){
    let that = this;
    this.heightArr = [];
    let h = 0;
    const query = wx.createSelectorQuery();
    query.selectAll(".box").boundingClientRect();
    query.exec(function(res){
        res[0].forEach((item)=>{
            h += item.height;
            that.heightArr.push(h);
        })
    })
  },
  scrollEvent(event){
    if(this.heightArr.length == 0){
        return;
    }
    let scrollTop = event.detail.scrollTop;
    let current = this.data.currentLeft;
    if(scrollTop >= this.distance){
        if(current + 1 < this.heightArr.length && scrollTop >= this.heightArr[current]){ 
            this.setData({
              currentLeft:current + 1
            })
        }
    }
    else{
        if(current - 1 >= 0 && scrollTop < this.heightArr[current - 1]){
            this.setData({
              currentLeft:current - 1
            })
        }
    }
    this.distance = scrollTop;
  },
  showInformation:function(){
    this.setData({
        mut:!this.data.mut
    })
  },
  selectMenu(ev){
    let index = ev.currentTarget.dataset.index
    this.setData({
      toView: "to" + index,
      currentLeft: index
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      wx.request({
        url: 'http://localhost:8000/goods',  //获取数据
        success:(res)=>{
          
           // console.log(res.data)
            this.setData({
                alllist:res.data
            })
            this.selectHeight()
        }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
/*
    this.mCurrent++

    wx.request({
      url: 'http://localhost:8000/goods?_page='+this.mCurrent+'&_limit=2',
      success:(res)=>{
        console.log(res.data)
        this.setData({
            alllist:[...this.data.alllist,...res.data]
        })
        console.log(this.data.alllist)
    }
  })*/

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})